<template>
  <view class="pull-refresh" :style="{ height: containerHeight }">
    <!-- 刷新状态区域 -->
    <view class="refresh-header" :style="{ height: headerHeight }">
      <view class="loading-icon" v-if="isLoading">
        <uni-loading-icon type="spinner" size="24"></uni-loading-icon>
      </view>
      <view class="refresh-text" v-else>
        {{ pullText }}
      </view>
    </view>
    
    <!-- 内容区域 -->
    <scroll-view
      class="scroll-content"
      :scroll-y="true"
      :refresher-enabled="true"
      :refresher-threshold="80"
      :refresher-default-style="false"
      @refresherpulling="onPulling"
      @refresherrefresh="onRefresh"
      @refresherrestore="onRestore"
      @refresherabort="onAbort"
    >
      <slot></slot>
    </scroll-view>
  </view>
</template>

<script>
export default {
  props: {
    // 刷新回调函数
    onRefresh: {
      type: Function,
      required: true
    },
    // 容器高度，默认100%
    containerHeight: {
      type: String,
      default: '100%'
    }
  },
  data() {
    return {
      headerHeight: '0rpx',
      isLoading: false,
      pullText: '下拉刷新'
    }
  },
  methods: {
    // 下拉过程中
    onPulling(e) {
      this.headerHeight = `${e.detail.dy}rpx`
      if (e.detail.dy > 80) {
        this.pullText = '松开刷新'
      } else {
        this.pullText = '下拉刷新'
      }
    },
    // 开始刷新
    async onRefresh() {
      this.isLoading = true
      this.pullText = '刷新中...'
      this.headerHeight = '80rpx'
      
      // 执行父组件传入的刷新逻辑
      try {
        await this.onRefresh()
      } catch (e) {
        console.error('刷新失败:', e)
      } finally {
        this.finishRefresh()
      }
    },
    // 结束刷新
    finishRefresh() {
      this.isLoading = false
      this.pullText = '刷新完成'
      setTimeout(() => {
        this.headerHeight = '0rpx'
        this.pullText = '下拉刷新'
      }, 500)
    },
    // 回到初始状态
    onRestore() {
      this.headerHeight = '0rpx'
    },
    // 取消刷新
    onAbort() {
      this.headerHeight = '0rpx'
    }
  }
}
</script>

<style scoped>
.pull-refresh {
  width: 100%;
  overflow: hidden;
  position: relative;
}

.refresh-header {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: height 0.3s;
  overflow: hidden;
}

.loading-icon {
  color: #666;
}

.refresh-text {
  color: #666;
  font-size: 28rpx;
}

.scroll-content {
  width: 100%;
  min-height: 100%;
}
</style>